package com.douhulu.bytedance.common.util.http;

import com.douhulu.bytedance.common.enums.ByteType;
import com.douhulu.bytedance.common.error.ByteError;
import com.douhulu.bytedance.common.error.ByteErrorException;
import com.douhulu.bytedance.common.util.http.apache.ApacheSimplePostRequestExecutor;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;

/**
 * <h2> 奕泽云 -  </h2>
 *
 * @Author: 奕泽云 - 曾庆雷
 * @Email: 75881401@qq.com
 * @Since: 2022-05-01 16:02
 * CopyRight：山西威斯汀文化传播有限公司
 */
public abstract class SimplePostRequestExecutor<H, P> implements RequestExecutor<String, String> {

    protected RequestHttp<H, P> requestHttp;

    public SimplePostRequestExecutor(RequestHttp requestHttp) {
        this.requestHttp = requestHttp;
    }

    @Override
    public void execute(String uri, Map<String, String> headers, String data, ResponseHandler<String> handler, ByteType byteType)
            throws ByteErrorException, IOException {
        handler.handle(this.execute(uri, headers, data, byteType));
    }

    public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
        if (requestHttp.getRequestType() == HttpType.APACHE_HTTP) {
            return new ApacheSimplePostRequestExecutor(requestHttp);
        }
        throw new IllegalArgumentException("非法请求参数");
    }

    @NotNull
    public String handleResponse(ByteType byteType, String responseContent) throws ByteErrorException {
        if (responseContent.isEmpty()) {
            throw new ByteErrorException("无响应内容");
        }
        ByteError error = ByteError.fromJson(responseContent, byteType);

        if (error.getErrorCode() != 0) {
            throw new ByteErrorException(error);
        }
        return responseContent;
    }
}
